import _ from 'lodash';

export default class EventHandler {
  dom;
  callbacks;

  constructor(dom) {
    this.dom = dom || document;
    this.callbacks = {};
  }

  on(event, callback) {
    const [eventName] = event.split('.');

    this.callbacks[event] = callback;
    this.dom.addEventListener(eventName, callback);
  }

  off(eventName) {
    if (eventName) {
      this.removeListener(eventName);
    } else {
      const eventNames = _.keys(this.callbacks);

      eventNames.forEach(name => {
        this.removeListener(name);
      });
    }
  }

  removeListener(eventName) {
    const [domEventName] = eventName.split('.');

    this.dom.removeEventListener(domEventName, this.callbacks[eventName]);
    delete this.callbacks[eventName];
  }
}